<?php
class LopsController extends AppController {

	var $name = 'Lops';
	var $uses = array('Lop','Giangvien');
	

	function index() {
		$this->Lop->recursive = 0;
		$this->set('lops', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid lop', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('lop', $this->Lop->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Lop->create();
			if ($this->Lop->save($this->data)) {
				$this->Session->setFlash(__('Lớp mới được tạo!', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Chưa điền đủ thông tin. Thử lại!', true));
			}
		}
		$this->Lop->Nganh->displayField = 'tenNganh';
		$nganhs = $this->Lop->Nganh->find('list');
		$this->set(compact('nganhs'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid lop', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Lop->save($this->data)) {
				$this->Session->setFlash(__('Lưu thành công!', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Không thể lưu dữ liệu. Kiểm tra lại!', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Lop->read(null, $id);
		}
		$this->Lop->Nganh->displayField='tenNganh';
		$nganhs = $this->Lop->Nganh->find('list');
		$this->set(compact('nganhs'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for lop', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Lop->delete($id)) {
			$this->Session->setFlash(__('Lop deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Lop was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
function themcovan(){
		if(!empty($this->data))
		{
			$err = false;
			foreach ($this->data['Lop']['lop'] as $value)
			{
				$giangvien_id = $this->data['Lop']['giangvien'][$value];
				if(!empty($giangvien_id))
				{
			$this->Lop->create();
			if(!$this->Lop->updateAll(array('giangvien_id'=>$giangvien_id),array('Lop.id'=>$value)))//dung update de cap nhat lai
			{
				$err = true;
				
			}
				}
		}
		if($err ===false)
			$this->Session->setFlash('Đã Lưu');
		else 
			$this->Session->setFlash('Lỗi Lưu không thành công!');
		$this->redirect(array('action'=>'themcovan'));
		}
		$lops = $this->Lop->find('list',array('conditions'=>array('giangvien_id'=>null),'fields'=>'tenLop'));
		//debug($lops);
		$giangviens = $this->Giangvien->find('list',array('fields'=>array('tenGV')));
		//debug($giangviens);
		$this->set(compact('lops','giangviens'));
		
		
		//debug($cvs);
		
	}
}
